package destiny.music;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpDownLoader {
	
	private URL url = null;
	
	public String downLoad(String urlStr)
	{
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buf = null;
		try {
			url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			buf = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			while((line = buf.readLine())!=null)
			{
				sb.append(line).append("\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally
		{
			try {
				buf.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return sb.toString();
	}
	public int downFile(String path,String urlStr,String fileName)
	{
		InputStream input = null;
		FileUit fileU = new FileUit();
		if(fileU.isFileExist(path+fileName))
		{
			return 1;
		}
		else
		{
			try {
				input = getInputStreamFromURL(urlStr);
				File rFile = fileU.writeToSDFromInput(path,fileName,input);
				if(rFile==null)
				{
					return -1;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally
			{
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return 0;
	}
	public InputStream getInputStreamFromURL(String urlStr) throws IOException
	{

			url = new URL(urlStr);
			HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
			InputStream input = urlConn.getInputStream();
			return input;
	}
}
